package com.gmall.console.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmall.console.common.JwtUtil;
import com.gmall.console.config.RedisConfig;
import com.gmall.console.system.entity.Menu;
import com.gmall.console.system.entity.User;
import com.gmall.console.system.entity.UserRole;
import com.gmall.console.system.mapper.MenuMapper;
import com.gmall.console.system.mapper.UserMapper;
import com.gmall.console.system.mapper.UserRoleMapper;
import com.gmall.console.system.service.IMenuService;
import com.gmall.console.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Jone
 * @since 2024-05-28
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private IMenuService iMenuService;
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public Map<String, Object> login(User user) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,user.getUserName());
        //wrapper.eq(User::getPassword,user.getPassword());
        User loginUser = this.baseMapper.selectOne(wrapper);
        if(null == loginUser){
            return null;
        }
        //比较加密后的密码是否相等
        if(!passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
            return null;
        }

        //token存储到redis中,保存60分钟
        loginUser.setPassword(null);
        //String token = "user:"+ UUID.randomUUID();
        //使用jwt 创建 token
        String token = jwtUtil.createToken(loginUser);

        redisTemplate.opsForValue().set(token,loginUser,60, TimeUnit.MINUTES);

        Map<String, Object> map = new HashMap<>();
        map.put("token",token);

        return map;
    }

    @Override
    public Map<String,Object> getUserInfo(String token) {

        //根据token获取用户信息
        Object obj = redisTemplate.opsForValue().get(token);

        User loginUser = jwtUtil.parseToken(token, User.class);

        if(null != loginUser){
            //反序列化
            //User loginUser = JSON.parseObject(JSON.toJSONString(obj),User.class);

            Map<String, Object> data = new HashMap<>();
            data.put("name",loginUser.getUserName());
            data.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            //获取角色
            List<String> list = new ArrayList<>();
            list.add("admin");
            data.put("roles",list);

            //权限菜单
            List<Menu> menuListByUser = iMenuService.getMenuListByUser(loginUser.getId());
            data.put("menuList",menuListByUser);

            return data;
        }

        return null;
    }

    @Override
    public void logout(String token) {
        //用jwt就不需要这个了
        //redisTemplate.delete(token);
    }

    @Override
    public void addUser(User user) {

        this.baseMapper.insert(user);

        List<String> roleIdList = user.getRoleIdList();
        if(null != roleIdList){
            for (String roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public User getUserById(String id) {

        User user = this.baseMapper.selectById(id);

        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleMapper.selectList(wrapper);

        List<String> collect = userRoles.stream().map(e -> e.getRoleId()).collect(Collectors.toList());
        user.setRoleIdList(collect);

        return user;
    }

    @Override
    public void updateUserById(User user) {

        this.baseMapper.updateById(user);

        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(wrapper);

        List<String> roleIdList = user.getRoleIdList();
        if(null != roleIdList){
            for (String roleId : roleIdList) {
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public void removeUserById(String id) {

        this.baseMapper.deleteById(id);

        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId,id);
        userRoleMapper.delete(wrapper);

    }

    @Override
    public List<User> getUserList(Integer total, Integer index) {
        return userMapper.getUserList(total,index);
    }

}
